package org.xu.upms.client;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xu.upms.client.rpc.AuthenticationRpcService;
import org.xu.upms.client.rpc.RpcUser;

public class SsoFilter extends ClientFilter{
	private static final String SSO_TOKEN_NAME = "token";

	@Override
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//1.校验请求中的token，Session中token
		//2.session中不存在token,
		   //(1).获取单点登录服务端回传token参数且验证， 保存认证信息到Session
		   //(2).验证失败，跳转到登录界面
		//3.session中存在token,验证token,已登录
		//4.跳转到登录界面
		
		String token = getLocalToken(request);
		if(token==null){
			if(getParameterToken(request)!=null){
				//
				// 再跳转一次当前URL，以便去掉URL中token参数
				response.sendRedirect(request.getRequestURL().toString());
			}else{
				//跳转到登录界面
				redirectLogin(request,response);
			}
		}else if(isLogin(token)){
			chain.doFilter(request, response);
		}else{
			//跳转到登录界面
			redirectLogin(request,response);
		}
	}

	
	public String getLocalToken(HttpServletRequest request){
		SessionUser	sessionUser = SessionUtils.getSessionUser(request);
		return sessionUser == null ? null : sessionUser.getToken();
	}
	
	public String getParameterToken(HttpServletRequest request){
		String token  = request.getParameter(SSO_TOKEN_NAME);
		//if(token!=null){
			RpcUser rpcUser = authenticationRpcService.findAuthInfo(token);
			if(rpcUser!=null){
				invokeAuthenticationInfoInSession(request,rpcUser.getToken(),rpcUser.getAccount());
				return rpcUser.getToken();
			}
		//}
		return null;
	}
	/**
	 * 认证信息保存到session中
	 * @param request
	 * @param token
	 * @param account
	 */
	private void invokeAuthenticationInfoInSession(HttpServletRequest request, String token, String account) {
		SessionUtils.setSessionUser(request, new SessionUser(token,account));
	}
	
	public void redirectLogin(HttpServletRequest request,HttpServletResponse response) throws IOException{
		SessionUtils.invalidate(request);
	  String url= new StringBuilder().append(ssoServerUrl).append("/login?backUrl=")
			  .append(request.getRequestURL().toString()).append("&appCode=").append(ssoAppCode).toString();
	  //http://localhost:8081/xu-upms-server/login?backUrl=http://localhost:8081/xu-upms-demo/index&appCode=ssoAppCode
	  response.sendRedirect(url);
	  
	}
	
	public boolean isLogin(String token){
		//检验token是否有效  是否过期
		return authenticationRpcService.validate(token);
	}
}
